# -*- coding:utf-8 -*-
# @Time  : 2019/11/18 16:33
# @Author: wangxb
'''
模块功能说明：
1、删除已存在的classes-dex2jar.src.zip压缩包
2、读取zip压缩包中的classes.dex文件，并根据classes.dex文件生成jar包
3、调用jd-gui.exe工具反编译jar
'''

import os
import re
import shutil
import subprocess
import zipfile


def generateJarFile(apk_zip_file_path, lanchon_tools_path, classes_file):
    '''
    1、读取zip压缩包中的classes.dex文件，并根据classes.dex文件生成jar包
    2、调用jd-gui.exe工具反编译jar
    :param self:
    :return:
    '''

    # 从zip包中读取classes.dex文件
    getClassesFileFromZip(apk_zip_file_path, classes_file, lanchon_tools_path)

    # 判断jar包是否存在,存在则删除
    jar_file = lanchon_tools_path + os.sep + 'classes-dex2jar.jar'
    if os.path.exists(jar_file):
        os.remove(jar_file)
    # 执行cmd，根据classes.dex文件生产对应的jar
    print("#######################Start running d2j-dex2jar.bat#######################")
    os.system(lanchon_tools_path[0:1] + ": && cd " + lanchon_tools_path + " && d2j-dex2jar.bat classes.dex")
    print("#######################Finished dex2jar####################################")


def copyAPKToZip(apk_file_path, zip_file_path):
    '''
    复制apk文件到zip
    :param apk_file_path:
    :param zip_file_path:
    :return:
    '''
    shutil.copy(apk_file_path, zip_file_path)


def getClassesFileFromZip(apk_zip_file_path, classes_file, lanchon_tools_path):
    zipFile = zipfile.ZipFile(apk_zip_file_path, 'r')
    try:
        # 判断lanchon工具文件夹中classes.dex是否存在,存在则删除
        # lanchon_classes_file = lanchon_tools_path + os.sep + 'classes.dex'
        # if os.path.exists(lanchon_classes_file):
        #     os.remove(lanchon_classes_file)
        # 从zip文件中读取classes.dex文件并存到dex-tools-lanchon路径中
        data = zipFile.read(classes_file)
        # 输入data数据到class_file_path中
        (lambda f, d: (f.write(d), f.close()))(open(lanchon_tools_path + "\classes.dex", 'wb'), data)
    except BaseException:
        print("Error: zip package not found:" + classes_file)
    finally:
        zipFile.close()


def examClassesFileInZip(apk_zip_file_path, classes_file):
    '''
    classes.dex文件不存在，返回0，存在返回1
    :param zip_file_path:
    :param classes_file:
    :return:
    '''
    try:
        zipFile = zipfile.ZipFile(apk_zip_file_path, 'r')
        zipFile.read(classes_file)
    except BaseException:
        return 0
    else:
        return 1


def getAllClassesFileInAPK(apk_zip_file_path):
    '''
    获取apk对应的zip包中所有的classes.dex文件
    :return:
    '''
    classes_list = []
    for i in range(30):
        i = i + 1
        if i == 1:
            classesFile = 'classes.dex'
        else:
            classesFile = 'classes' + '%d' % i + '.dex'
        # 如果classes.dex文件存在则添加到classes_list数组中
        if examClassesFileInZip(apk_zip_file_path, classesFile) == 1:
            classes_list.append(classesFile)
    for lis in classes_list:
        print(lis)
    return classes_list


def changeFileSuffix(apk_file_path):
    '''
    修改文件后缀
    :return:
    '''
    portion = os.path.splitext(apk_file_path)
    # 如果后缀是.apk
    if portion[1] == ".apk":
        # 重新组合文件名和后缀名
        zipname = portion[0] + ".zip"
        return zipname


def getAPKPackage(apk_file_path):
    '''
    获取apk的包名
    :return:
    '''
    command = 'aapt dump badging ' + apk_file_path
    file_content = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).stdout.read().decode('utf-8')
    searchObj = re.search(r'package: name=\'(.*)\' versionCode=\'',
                          file_content,
                          re.M | re.I)
    # print('PackageName:\n' + searchObj.group(1)+'\n')
    return searchObj.group(1)


def examZipFile(jar_zip_file_path):
    '''
    判断dex2jar的zip包是否存在,存在则删除
    :return:
    '''
    zip_file = jar_zip_file_path + os.sep + 'classes-dex2jar.src.zip'
    if os.path.exists(zip_file):
        os.remove(zip_file)


def killJdgui():
    '''
    检测jd-gui.exe工具是否存在，存在则结束进程
    :return:
    '''
    ifrun = os.system('tasklist | findstr "jd-gui"')
    if 0 == ifrun:
        os.system('taskkill /im jd-gui.exe')

# if __name__ == '__main__':
#
#     # 读取apk文件生成对应的jar包,并调用jd-gui.exe反编译jar
#     generateJarFile()
#     #判断zip文件是否存在，存在则删除
#     examZipFile()
#
#     t = JdguiThread("jdguiThread")
#     t.start()
#     time.sleep(2)
#     t2 = KeyboardThread("keyboardThread")
#     t2.start()
#     print("Finished decompile the Jar")
